<template>
  <div class="inbound-order-container">
    <!-- 入库订单列表 -->
    <el-table 
      :data="currentPageData" 
      border 
      stripe 
      fit 
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="_id" label="订单ID" min-width="220" show-overflow-tooltip />
      <el-table-column prop="productName" label="商品名称" min-width="180" />
      <el-table-column prop="quantity" label="入库数量" width="120" align="center" />
      <el-table-column prop="supplier" label="供应商" min-width="180" />
      <el-table-column prop="status" label="订单状态" width="150" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="200" align="center">
        <template #default="scope">
          {{ formatTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <!-- 待审核状态：显示审核按钮（弹出对话框） -->
          <el-button 
            v-if="scope.row.status === '待审核'" 
            type="info" 
            size="small"
            @click="showApproveDialog(scope.row._id)"
          >审核</el-button>

          <!-- 审核不通过状态：显示重新审核按钮 -->
          <el-button 
            v-if="scope.row.status === '审核不通过'" 
            type="primary" 
            size="small"
            @click="handleReAudit(scope.row._id)"
          >重新审核</el-button>

          <!-- 待入库状态：显示确认入库按钮 -->
          <el-button 
            v-if="scope.row.status === '待入库'" 
            type="warning" 
            size="small"
            @click="handleConfirm(scope.row._id)"
          >确认入库</el-button>
          <!-- 查看详情 -->
          <el-button type="text" size="small" @click="handleViewDetail(scope.row._id)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
     <div class="pagination-container">
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper, ->, total"
      @current-change="handleCurrentChange"
      style="margin-top: 20px;"
    />
  </div>
    <!-- 审核对话框 -->
    <el-dialog 
      title="审核入库订单" 
      v-model="approveDialogVisible"
      width="30%"
    >
      <p>确定要审核当前入库订单吗？</p>
      <template #footer>
        <!-- 添加flex布局容器实现左右排列 -->
        <div style="display: flex; justify-content: space-between; width: 100%;">
          <el-button type="danger" @click="handleReject(currentOrderId)">不通过</el-button>
          <el-button type="success" @click="handleApprove(currentOrderId)">通过</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { logisticsApi } from '@/api/logistics'
import dayjs from 'dayjs'  // 需安装dayjs处理时间格式
const currentPage = ref(1)  // 当前页（初始为1）
const pageSize = ref(10)    // 每页显示10条（固定值）
const total = ref(0)        // 总数据量（等于purchaseOrders长度）
import { useRouter } from 'vue-router'
const router = useRouter()

const handleViewDetail = (id) => {
  //跳转 到详情页面
  router.push({ path: `/inOrderDetail/${id}` })
  
}
// 计算当前页数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return inboundOrders.value.slice(start, end)  // 切片获取当前页数据
})
// 分页切换
const handleCurrentChange = (val) => {
  currentPage.value = val  // 更新当前页
}
// 入库订单列表数据
const inboundOrders = ref([])
// 审核对话框显示状态
const approveDialogVisible = ref(false)
// 当前审核的订单ID
const currentOrderId = ref('')

// 初始化加载订单列表
onMounted(async () => {
  await fetchInboundOrders()
})

// 获取入库订单列表
const fetchInboundOrders = async () => {
  try {
    const res = await logisticsApi.getInboundOrdersList()
    inboundOrders.value = res  // 假设接口直接返回订单数组
    total.value = res.length 
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '获取入库订单列表失败')
  }
}

// 显示审核对话框
const showApproveDialog = (id) => {
  currentOrderId.value = id
  approveDialogVisible.value = true
}

// 审核通过（调整为接收当前订单ID）
const handleApprove = async (id) => {
  try {
    await logisticsApi.approveInboundOrder(id)
    ElMessage.success('审核通过，库存已更新')
    approveDialogVisible.value = false
    await fetchInboundOrders()  // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '审核通过失败')
  }
}

// 审核不通过（调整为接收当前订单ID）
const handleReject = async (id) => {
  try {
    await logisticsApi.rejectInboundOrder(id)
    ElMessage.success('审核不通过')
    approveDialogVisible.value = false
    await fetchInboundOrders()  // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '审核不通过失败')
  }
}

// 重新审核（保持不变）
const handleReAudit = async (id) => {
  try {
    console.log(id);
    
    await logisticsApi.reAuditInboundOrder(id)
    ElMessage.success('已重新提交审核')
    await fetchInboundOrders()  // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '重新审核失败')
  }
}

// 确认入库（保持不变）
const handleConfirm = async (id) => {
  try {
    await logisticsApi.confirmInboundOrder(id)
    ElMessage.success('入库确认成功')
    await fetchInboundOrders()  // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '确认入库失败')
  }
}

// 状态标签颜色映射（保持不变）
const getStatusTagType = (status) => {
  const map = {
    '待审核': 'info',
    '已入库': 'success',
    '审核不通过': 'danger',
    '待入库': 'warning'
  }
  return map[status] || 'default'
}

// 时间格式化（需安装dayjs）
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.inbound-order-container {
  padding: 20px;
}

.el-table .el-button {
  margin: 0 5px;
}
.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  text-align: center; /* 水平居中 */
  margin: 20px 0; /* 调整上下边距 */
}

/* 可选：调整分页组件内间距 */
.el-pagination {
  padding: 10px 20px; /* 增加内边距使组件更饱满 */
}
</style>